/***************************************************************
 *
 * Filename：SubWindow.cpp
 * Abstract：the design of chatting window
 * version ：1.0
 * 
 * Copyright (c) 2011 SCUT DT&P FY&XC
 * 
***************************************************************/ 

#include "SubWindow.h"

//构造函数，初始化登录窗口
SubWindow::SubWindow(Serve *ser, QString str)
{
        service = ser;
	msgmng = new MessagePRO;
        s=str.split(":");
	qDebug()<<"s.at(0) address:"<<s.at(0);
	msgmng->username = s.at(1);
	msgmng->hostname = s.at(1);
	msgmng->address = (QHostAddress)s.at(0);
        initialize();
        connect(service, SIGNAL(msgSendMsg(MessagePRO *)) , this, SLOT(slotshowMessage(MessagePRO *)));
        connect(service, SIGNAL(msgRevcFileName(MessagePRO *)) , this, SLOT(slotRevcFile(MessagePRO *)));
        connect(service, SIGNAL(msgRefuseFile(MessagePRO *)) , this, SLOT(slotRefuseFile(MessagePRO *)));
}

//初始化聊天室界面和程序基本信息
void SubWindow::initialize()
{
	
	resize(620,600);
        //QSound::play("./sound/Global.wav");
	setMinimumSize(620,600);
        setMaximumSize(620,600);
        setWindowTitle(tr("chating to %1").arg(msgmng->hostname));

	messageWindow = new QWidget(this);
	messageWindow->resize(620,600);
	messageWindow->setMinimumSize(620,600);
	messageWindow->setMaximumSize(620,600);
	
	recordTextEdit = new QTextEdit(messageWindow);
	recordTextEdit->setReadOnly(true);
	recordTextEdit->setMinimumSize(600,300);

	inputTextEdit = new QTextEdit(messageWindow);
	inputTextEdit->setMinimumSize(490,100);
	inputTextEdit->setMaximumSize(600,180);

	editToolBar = new QToolBar(messageWindow);

	//编辑工具栏上的字体
	fontComboBox = new QComboBox(editToolBar);
	editToolBar->addWidget(fontComboBox);
	fontComboBox->setEditable(true);
	QFontDatabase fontDB;
	fontComboBox->addItems(fontDB.families());
	connect(fontComboBox, SIGNAL(activated(const QString &)),
        this, SLOT(slotsetFontFamily(const QString &)));
	fontComboBox->setCurrentIndex(fontComboBox->findText(QApplication::font().family()));
        qDebug()<<fontComboBox->currentIndex()<<fontComboBox->currentText();
	//编辑工具栏的字体大小
	sizeComboBox = new QComboBox(editToolBar);
	editToolBar->addWidget(sizeComboBox);
	sizeComboBox->setEditable(true);
	foreach(int size, fontDB.standardSizes())
		sizeComboBox->addItem(QString::number(size));
	connect(sizeComboBox, SIGNAL(activated(const QString &)),
                this, SLOT(slotsetFontSize(const QString &)));
	sizeComboBox->setCurrentIndex(sizeComboBox->findText(QString::number(QApplication::font().pointSize())));

	//粗体
	boldButton = new QToolButton(editToolBar);
	editToolBar->addWidget(boldButton);
	boldButton->setCheckable(true);
	boldButton->setIcon(QIcon(":/image/textbold.png"));
	connect(boldButton, SIGNAL(toggled(bool)), this, SLOT(slotsetBoldFont(bool)));

	//斜体
	italicButton = new QToolButton(editToolBar);
	editToolBar->addWidget(italicButton);
	italicButton->setCheckable(true);
	italicButton->setIcon(QIcon(":/image/textitalic.png"));
        connect(italicButton, SIGNAL(toggled(bool)), inputTextEdit, SLOT(setFontItalic(bool)));

	//下划线
	underlineButton = new QToolButton(editToolBar);
	editToolBar->addWidget(underlineButton);
	underlineButton->setCheckable(true);
	underlineButton->setIcon(QIcon(":/image/textunder.png"));
        connect(underlineButton, SIGNAL(toggled(bool)), inputTextEdit, SLOT(setFontUnderline(bool)));

	//颜色
	colorButton = new QToolButton(editToolBar);
	editToolBar->addWidget(colorButton);
	colorButton->setIcon(QIcon(":/image/textcolor.png"));
	connect(colorButton, SIGNAL(clicked()), this, SLOT(slotsetFontColor()));

	//打开图片
	imageButton = new QToolButton(editToolBar);
	editToolBar->addWidget(imageButton);
	imageButton->setIcon(QIcon(":/image/openimage.png"));
	connect(imageButton, SIGNAL(clicked()), this, SLOT(slotopenImage()));
	
	//发送文件
	fileButton = new QToolButton(editToolBar);
	editToolBar->addWidget(fileButton);
	fileButton->setIcon(QIcon(":/image/file.png"));
        connect(fileButton, SIGNAL(clicked()), this, SLOT(slotopenFileWindow()));

	//发送按钮
	sendButton = new QPushButton(tr("&Send"), messageWindow);
	sendButton->setEnabled(false);
	connect(inputTextEdit, SIGNAL(textChanged()), this, SLOT(slotenabledSendButton()));
	connect(sendButton, SIGNAL(clicked()), this, SLOT(slotsendMessage()));

	//关于按钮
	aboutButton = new QPushButton(tr("&About"),messageWindow);
        connect(aboutButton, SIGNAL(clicked()), this, SLOT(slotabout()));


	//退出按钮
	quitButton = new QPushButton(tr("&Quit"),messageWindow);
	connect(quitButton,SIGNAL(clicked()), this, SLOT(close()));
			
	//布局
	QHBoxLayout *buttonLayout = new QHBoxLayout;
	buttonLayout->addWidget(aboutButton);
	buttonLayout->addStretch(3);
	buttonLayout->addWidget(sendButton);
	buttonLayout->addStretch(1);
	buttonLayout->addWidget(quitButton);

	QVBoxLayout *leftLayout = new QVBoxLayout;
	leftLayout->addWidget(recordTextEdit);
	leftLayout->addWidget(editToolBar);
	leftLayout->addWidget(inputTextEdit);

	QGridLayout *mainLayout = new QGridLayout;
	mainLayout->addLayout(leftLayout,0,0);
	//mainLayout->addWidget(userListWidget,0,1);
	mainLayout->addLayout(buttonLayout,1,0,1,2);
	mainLayout->setSizeConstraint(QLayout::SetFixedSize);

	messageWindow->setLayout(mainLayout);
	messageWindow->show();
}

//槽函数，聊天信息显示
void SubWindow::slotshowMessage(MessagePRO *msg)
{
        //qDebug<<msg<<"in slotshowmessage";
        //qDebug<<m<<"in slotshowmessage";
    if(msg->address == msgmng->address ){
        qDebug()<<"["<<QDateTime::currentDateTime().toString("yyyy-MM-dd  hh:mm:ss")<<"]  "<<msg->username<<":\n"<<msg->extend;
	recordTextEdit->append("[" + QDateTime::currentDateTime().toString(tr("yyyy-MM-dd  hh:mm:ss"))
		                                        + tr("]  ") +msg->username+" :");
	recordTextEdit->append(msg->extend);
    }
}
	
//槽函数，处理关闭事件
void SubWindow::closeEvent(QCloseEvent *event)
{
	//广播用户注销信息
	/*MessagePRO *msg = new MessagePRO;
	msg->command = IPMSG_BR_EXIT;
	msg->extend="";
	service->broadcast(6291458, NULL);*/

	QString str=msgmng->address.toString()+":"+msgmng->username;
	emit delSub(str);
	qDebug()<<"emit delSub(str)";
	//service->udpSocket->close();
	//接受信号，执行退出
	event->accept();
}

//槽函数，发送消息
void SubWindow::slotsendMessage()
{	
	qDebug()<<"sendMessage():"<<msgmng->hostname<<":"<<msgmng->username;
        if(msgmng->hostname.endsWith("*")) {
	        message = inputTextEdit->toHtml();
                qDebug()<<"to html in SubWindow";
        }
        else {
		message = inputTextEdit->toPlainText();
                qDebug()<<"to plainText in SubWindow";
        }
        //message = inputTextEdit->toPlainText();
        //message = message.toLocal8Bit(textmsg);
	recordTextEdit->append("[" + QDateTime::currentDateTime().toString(tr("yyyy-MM-dd  hh:mm:ss"))
		                                        + tr("]  ") + (QHostInfo::localHostName()));
	recordTextEdit->append(message);
	//connect(fontComboBox, SIGNAL(activated(const QString &)),inputTextEdit, SLOT(setFontFamily(const QString &)));
	MessagePRO *msg = new MessagePRO;
	msg->command=288;
	msg->extend=message;
	msg->address=msgmng->address;
	qDebug()<<"sendMessage() MessagePRO->address"<<msgmng->address;
	qDebug()<<"sendMessage() msg->address"<<msg->address;
        bool flag;
        if (msgmng->username.endsWith("*")) {
            flag = false;
        }
        else {
            flag = true;
        }
        service->sendUdp(msg,flag);
	qDebug()<<"End of sendUdp";
	//清除发送框
        inputTextEdit->clear();

}

//槽函数，关于本程序
void SubWindow::slotabout()
{
	QMessageBox::information(this, tr("About"),tr("This project is on Linux+QT4 platform, which was used for transfer files on Internet, providing communication with IP MSG, FeiQ or other clients. \nBY GXC in DT&P"));
}

//槽函数，激活发送按钮
void SubWindow::slotenabledSendButton()
{
	sendButton->setEnabled(true);
}

//槽函数，设置字体颜色
void SubWindow::slotsetFontColor()
{
	QColor col = QColorDialog::getColor(inputTextEdit->textColor(), this);
	if (!col.isValid())
	{
		return;
	}
	inputTextEdit->setTextColor(col);
	
	QPixmap pix(16, 16);
	pix.fill(col);
	colorButton->setIcon(pix);
}

//槽函数，打开图片文件
void SubWindow::slotopenImage()
{
	//实现图像同步的策略为，先复制图像到自己和别人机器的 temp-image/ 下，然后在数据包中加入HTML的显示本地图像代码
	QString image = QFileDialog::getOpenFileName(this, tr("Open Image File..."),
			"temp-image/", tr("Image-Files (*.png *.gif *.bmp *.jpeg *.jpg)"));
	QFile::copy(image, QString("temp-image/") + QFileInfo(image).fileName());
	if (image.isEmpty())
	{
		return;
	}
	inputTextEdit->append("<img src='temp-image/" + QFileInfo(image).fileName() + "'  />");

	
	//广播图片	
	QByteArray datagram;
	QDataStream out(&datagram,QIODevice::WriteOnly);

	out << 4;

	out << QFileInfo(image).fileName();

	QImageReader imageReader(image);
	imageReader.setFormat(QFileInfo(image).suffix().toAscii());
	out <<  imageReader.read();
}

//槽函数，发送文件
void SubWindow::slotopenFileWindow()
{
    FSWin = new FileSendWindow(msgmng->address);  //
    //connect(FSWin, SIGNAL(delSub(QString)) , this, SLOT(delSub(QString)));
    connect(FSWin,SIGNAL(sendFileName(QString)),this,SLOT(sentFileName(QString)));
    connect(FSWin,SIGNAL(stopsendfile()),this,SLOT(slotstopsendfile()));
    FSWin->show();
    //subislist[str]=1;
}

//槽函数，发送文件名，启动TCP服务器
void SubWindow::sentFileName(QString filename)
{
    qDebug()<<"sentFileName():"<<msgmng->hostname<<":"<<msgmng->username;
    MessagePRO *msg = new MessagePRO();
    msg->command=96;
    msg->extend=filename;
    msg->address=msgmng->address;
    qDebug()<<"sendMessage() MessagePRO->address"<<msgmng->address;
    qDebug()<<"sendMessage() msg->address"<<msg->address;
    qDebug()<<"sendMessage() msg->extend"<<msg->extend;
    service->sendUdp(msg);
    qDebug()<<"End of sendfilename";
    //
    QString fn = FSWin->getfileName();
    tcpServer = new TCPServer(fn,FSWin);
}

//
void SubWindow::slotRevcFile(MessagePRO *msg)
{
    qDebug()<<"to create fileReveWindow in SubWindow::slotRevcFile";
    qDebug()<<"sendMessage() msg->extend"<<msg->extend;
    int btn = QMessageBox::information(this,tr("accept the file"),
                                     tr("come from \"%1\"`s file:%3,reve?")
                                     .arg(msg->username).arg(msg->extend),
                                     QMessageBox::Yes,QMessageBox::No);
    QString fileName = msg->extend;
    if(btn == QMessageBox::Yes)
            {
                QString name = QFileDialog::getSaveFileName(0,tr("to save the file"),fileName);
                if(!name.isEmpty())
                {
                    FRWin = new FileReveWindow();
                    FRWin->show();
                    tcpClient = new TCPClient(msg->address,name,FRWin);

                }

            }
    else{
        sendRefuseMsg();
    }
}
void SubWindow::sendRefuseMsg()
{
    qDebug()<<"send Refuse message";
    MessagePRO *msg = new MessagePRO;
    msg->command=99;
    //msg->extend=filename;
    msg->address=msgmng->address;
    qDebug()<<"sendMessage() MessagePRO->address"<<msgmng->address;
    qDebug()<<"sendMessage() msg->address"<<msg->address;
    qDebug()<<"sendMessage() msg->extend"<<msg->extend;
    service->sendUdp(msg);
    qDebug()<<"End of sendfilename";

}

//
void SubWindow::slotRefuseFile(MessagePRO *msg)
{
    tcpServer->refused();
    FSWin->close();
    qDebug()<<"slotrefusefile";
    QMessageBox::information(this,tr("accept the file"),
                                         tr("\"%1\" refuse to reve the file!!!!!")
                                         .arg(msg->username),
                                         QMessageBox::Yes);

}

//
void SubWindow::slotstopsendfile()
{
    delete tcpServer;
}

//槽函数，设置字体大小
void SubWindow::slotsetFontSize(const QString &size)
{
    qDebug()<<size;
    inputTextEdit->setFontPointSize(size.toFloat());
}

//槽函数，设置输入字体为粗体
void SubWindow::slotsetBoldFont(bool flag)
{
	if(flag == true)
	{
		inputTextEdit->setFontWeight(QFont::Bold);
	}
	else
		inputTextEdit->setFontWeight(QFont::Normal);
}

//槽函数，设置输入字
void SubWindow::slotsetFontFamily(const QString &)
{
	QString fontfamily = fontComboBox->currentText();
        qDebug()<<fontfamily<<"in SubWindow::slotsetFontFamily";
	inputTextEdit->setFontFamily(fontfamily);
}
